import axios from 'axios'
import { getToken } from './auth'
import { Message } from 'element-ui'
const service = axios.create({
  baseURL: 'https://api-hmzs.itheima.net/tj',
  timeout: 5000 // request timeout
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    const token = getToken()
    if (token) {
      config.headers.Authorization = token
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    // axios默认包裹了data
  // 判断是不是Blob
    if (response.data instanceof Blob) return response.data // 返回了Blob对象
    if (response.data.code !== 10000) {
      Message({
        message: response.data.msg,
        type: 'warning'
      })
      return Promise.reject(new Error(response.data.msg))
    }
    return response.data
  },
  error => {
    Message({
      message: error.response.data.msg,
      type: 'warning'
    })
    return Promise.reject(error)
  }
)

export default service
